import 'package:fish_redux/fish_redux.dart';

import '../utils.dart/storage.dart';
import 'action.dart';
import 'state.dart';

Reducer<LoginState> buildReducer() {
  return asReducer(
    <Object, Reducer<LoginState>>{
      Lifecycle.initState: _onInitState,
      LoginAction.clearUserName: _onClearUserName,
      LoginAction.clearPassword: _onClearPassword,
      LoginAction.checkUserName: _onCheckUserName,
      LoginAction.checkPassword: _onCheckPassword,
      LoginAction.checkLogin: _onCheckLogin
    },
  );
}

LoginState _onInitState(LoginState state, Action action) {
  final newState = state.clone();
  return newState
    ..userNameEditingController.text = sharedPreferences.getString('userName')
    ..userPwdEditingController.text = sharedPreferences.getString('userPwd');
}

LoginState _onClearUserName(LoginState state, Action action) {
  final newState = state.clone();
  return newState
    ..userPwdEditingController.text = ''
    ..isLoginEnable = false;
}

LoginState _onClearPassword(LoginState state, Action action) {
  final newState = state.clone();
  return newState
    ..userPwdEditingController.text = ''
    ..isLoginEnable = false;
}

LoginState _onCheckUserName(LoginState state, Action action) {
  final newState = state.clone();
  final errorString =
      _getUserNameErrorString(newState.userNameEditingController.text);
  return newState
    ..userNameErrorText = errorString
    ..isLoginEnable = errorString == null;
}

LoginState _onCheckPassword(LoginState state, Action action) {
  final newState = state.clone();
  final errorString =
      _getUserPasswordErrorString(newState.userPwdEditingController.text);
  return newState
    ..userNameErrorText = errorString
    ..isLoginEnable = errorString == null;
}

LoginState _onCheckLogin(LoginState state, Action action) {
  final newState = state.clone();
  final userNameErrorText =
      _getUserNameErrorString(newState.userNameEditingController.text);
  final userPasswordErrorText =
      _getUserPasswordErrorString(newState.userPwdEditingController.text);
  return newState
    ..userNameErrorText = userNameErrorText
    ..userPwdErrorText = userPasswordErrorText
    ..isLoginEnable =
        (userNameErrorText == null && userPasswordErrorText == null);
}

String _getUserNameErrorString(String userName) {
  if (userName == null || userName.isEmpty) return 'userName could not be null';
  if (RegExp(r'[1-9]{1,}').allMatches(userName).length == 0)
    return 'userName should be 0-9 digits';
  if (userName.length <= 6) return 'useName lenght should be more then size';
  return null;
}

String _getUserPasswordErrorString(String password) {
  if (password == null || password.isEmpty) return 'userName could not be null';
  if (RegExp(r'[1-9a-zA-Z]{1,}').allMatches(password).length == 0)
    return '0 to 6 digits and upper and lower case letters';
  if (password.length <= 6) return 'useName lenght should be more then size';
  return null;
}
